package com.szl.group.manager;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.szl.group.utils.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


@Slf4j
@Component
public class MailSendManager {

    /**
     * 发送者地址
     **/
    @Value("${spring.mail.username}")
    private String posterAddress;

    /**
     * 发送者
     **/
    private static final String posterName = "szl-app";

    @Autowired
    private JavaMailSender javaMailSender;


    /**
     * 文本发送
     **/
    public void sendEmailAsText(final EmailModel emailModel) {

        Assert.isNull(emailModel, "发送实体不能为空");
        List<EmailModel.Dev> list = emailModel.getDevs();
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(dev -> {
                MimeMessagePreparator mimeMessagePreparator = mimeMessage -> {
                    mimeMessage.setFrom(posterAddress);
                    mimeMessage.setRecipients(Message.RecipientType.TO, dev.getEmail());
                    mimeMessage.setText(
                            "<html><body>"
                                    + "hello：" + dev.getName()
                                    + "<br>" + "msg：" + emailModel.getEmailContent()
                                    + "<br>" + "from :" + posterName
                                    + "</body></html>");
                };
                try {
                    javaMailSender.send(mimeMessagePreparator);
                    log.info("邮箱已返送至[{}]邮箱！", dev.getName());
                } catch (MailException e) {
                    log.error("邮箱异常：{}", e);
                }
            });
        }


    }

    /**
     * html 网页发送
     * 该方法为异步方法
     **/
    @Async
    public void sendEmailAsSysExceptionHtml(final EmailModel emailModel) {

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        Assert.isNull(emailModel, "发送实体不能为空");
        List<EmailModel.Dev> list = emailModel.getDevs();
        if (CollectionUtils.isNotEmpty(list)) {

            MimeMessageHelper mimeMessageHelper = builderMessage(mimeMessage, posterAddress, emailModel);
            list.forEach(dev -> {
                try {
                    mimeMessageHelper.setTo(dev.getEmail());
                    javaMailSender.send(mimeMessage);
                    log.info("邮箱发送至[{}]邮箱！", dev.getName());
                } catch (MessagingException e) {
                    e.printStackTrace();
                } catch (MailException e) {
                    log.error("邮箱异常：{}", e);
                }
            });
        }
    }

    private MimeMessageHelper builderMessage(MimeMessage mimeMessage, String posterAddress, EmailModel emailModel) {

        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(posterAddress);
            mimeMessageHelper.setSubject(emailModel.getEmailTheme());
            mimeMessageHelper.setText("<!DOCTYPE html>\n" +
                            "<html>\n" +
                            "\t<head>\n" +
                            "\t\t<meta charset=\"UTF-8\">\n" +
                            "\t\t<title></title>\n" +
                            "\t</head>\n" +
                            "\t<style>\n" +
                            "\t\tbody,\n" +
                            "\t\ttable,\n" +
                            "\t\ttbody,\n" +
                            "\t\ttr {\n" +
                            "\t\t\tbackground-color: aquamarine;\n" +
                            "\t\t\tbackground-size: 100%;\n" +
                            "\t\t}\n" +
                            "\t</style>\n" +
                            "\n" +
                            "\t<body>\n" +
                            "\t\t<table border=\"solid 2 px\" align=\"center\" style=\"text-align: center;\">\n" +
                            "\t\t\t<tbody>\n" +
                            "\t\t\t\t<tr>\n" +
                            "\t\t\t\t\t<td width=\"200px\" bgcolor=\"coral\">时间</td>\n" +
                            "\t\t\t\t\t<td width=\"80%\" bgcolor=\"azure\">" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + "</td>\n" +
                            "\t\t\t\t</tr>\n" +
                            "\t\t\t\t<tr>\n" +
                            "\t\t\t\t\t<td width=\"200px\" bgcolor=\"coral\">信息</td>\n" +
                            "\t\t\t\t\t<td width=\"80%\" bgcolor=\"azure\">" + "测试" + "</td>\n" +
                            "\t\t\t\t</tr>\n" +
                            "\t\t\t\t<tr>\n" +
                            "\t\t\t\t\t<td width=\"200px\" bgcolor=\"coral\">堆栈</td>\n" +
                            "\t\t\t\t\t<td width=\"80%\" bgcolor=\"azure\" style=\"text-align: left;\">" + emailModel.getEmailContent() + "</td>\n" +
                            "\t\t\t\t</tr>\n" +
                            "\t\t\t</tbody>\n" +
                            "\t\t</table>\n" +
                            "\t</body>\n" +
                            "\n" +
                            "</html>"
                    , true);

            return mimeMessageHelper;
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
